<?php

namespace core;

class Url
{
    /**
     * 返回 http or https
     *
     * @param  boolean $full
     * @return string
     */
    public static function scheme(bool $full = false): string
    {
        if (isset($_SERVER['REQUEST_SCHEME'])) {
            return $_SERVER['REQUEST_SCHEME'] . ($full ? '://' : '');
        } elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
            return "https" . ($full ? '://' : '');
        } else {
            return "http" . ($full ? '://' : '');
        }
    }

    /**
     * 返回网址的域名部分 'x.com'
     *
     * @return string
     */
    public static function domain(): string
    {
        return filter_var($_SERVER['HTTP_HOST'], FILTER_SANITIZE_URL);
    }

    public static function query(): string
    {
        return explode('?', self::uri())[1] ?? '';
    }

    /**
     * 返回完整的主页地址
     *
     * @return string
     */
    public static function home(): string
    {
        return self::scheme(true) . self::domain();
    }

    /**
     * 返回完整的当前网址
     *
     * @param  boolean $resParams
     * @return string
     */
    public static function current(bool $resParams = false): string
    {
        return self::home() . self::uri($resParams);
    }

    /**
     * 返回网址的 uri
     *
     * @param  boolean $resParams
     * @return string
     */
    public static function uri(bool $resParams = false): string
    {
        $uri = self::server('REQUEST_URI');

        if (!$resParams) {
            $arr = explode('?', $uri);
            $uri = $arr[0];
        }

        return urldecode($uri);
    }

    public static function server($key = false)
    {
        if ($key) {
            return $_SERVER[$key] ?? false;
        } else if ($key == false) {
            return $_SERVER;
        }
    }
}
